package org.flexr.model
{
	import flash.desktop.NativeApplication;
	import flash.events.*;
	import flash.filesystem.*;
	
	import mx.controls.*;
	
	public class Config extends EventDispatcher
	{
		private var _config:XML;
		private var configFile:File;
		private static var _instance:Config; 
		
		public function Config(target:IEventDispatcher=null)
		{
			super(target);
			Config._instance = this;
			readConfig();
			NativeApplication.nativeApplication.addEventListener(Event.EXITING, onAppExit);

		}
 		private function readConfig():void
		{
			configFile = File.applicationStorageDirectory.resolvePath('config.xml');
 			if(configFile.exists)
			{
	 			var stream:FileStream = new FileStream();
	 			stream.open( configFile, FileMode.READ );
	 			_config = XML(stream.readUTFBytes(stream.bytesAvailable));
				stream.close();
			}
			else 
			{
				config = DefaultConfig.configXML;
			}
 		}
		public static function get instance():Config
		{
			if(Config._instance == null) new Config();
			return Config._instance;
		}
		private function onReady():void{}
		
		private function onError():void{}

		public function setConfig(field:String, value:String):void
		{}
		
		[Bindable] public function get config():XML
		{
			return _config;
		}
		public function set config(value:XML):void
		{
		 	this._config = value;
			writeConfig();
		}
 
		private function onAppExit(e:Event):void
		{
			writeConfig();
		}
		private function writeConfig():void{
 			var stream:FileStream = new FileStream();
 			configFile =new File(configFile.nativePath);
 			stream.open( configFile, FileMode.WRITE);
 			stream.writeUTFBytes(_config.toString());
 			stream.close();
		
		}
		
	}
}